/* treemap_bk.js - Revision: Preview Release 1.0 */

// Copyright (c) 2006. Bankinter S.A.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Bankinter nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.


var Bankinter; if (!Bankinter) Bankinter = {};
Bankinter.Utils; if (!Bankinter.Utils) Bankinter.Utils = {};
Bankinter.Graphics; if (!Bankinter.Graphics) Bankinter.Graphics = {};
Bankinter.Utils.Xml; if (!Bankinter.Utils.Xml) Bankinter.Utils.Xml = {};


Bankinter.Utils.Xml.msProgIDs = ["Microsoft.XMLHTTP", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "MSXML2.XMLHTTP.5.0"];

/////////////////////////////////////////////////////////////////////////////
// Funciones auxiliares de tratamiento de nodos XML
/////////////////////////////////////////////////////////////////////////////
Bankinter.Utils.Xml.getNodeText = function(node)
{
	var txt = "";
  
	if (!node)
		return;

	try
	{
		var child = node.firstChild;
 
		while (child)
		{
			try
			{
				if (child.nodeType == 3 /* TEXT_NODE */)
					txt += Bankinter.Utils.Xml.encodeEntities(child.data);
				else if (child.nodeType == 4 /* CDATA_SECTION_NODE */)
					txt += child.data;
			} 
			catch (e) 
			{ 
			}

			child = child.nextSibling;
		}
	}
	catch (e) 
	{ 
	}
  
	return txt;
};


Bankinter.Utils.Xml.nodeContainsElementNode = function(node)
{
	if (node)
	{
		node = node.firstChild;

		while (node)
		{
			if (node.nodeType == 1 /* Node.ELEMENT_NODE */)
				return true;

			node = node.nextSibling;
		}
	}
	return false;
};

Bankinter.Utils.Xml.encodeEntities = function(str)
{
	if (str && str.search(/[&<>"]/) != -1)
	{
		str = str.replace(/&/g, "&amp;");
		str = str.replace(/</g, "&lt;");
		str = str.replace(/>/g, "&gt;");
		str = str.replace(/"/g, "&quot;");
	}
	return str
};


Bankinter.Utils.Xml.DataSet = function(url, xpath, interval)
{
    this.url = url;
    this.xpath = xpath;
    this.interval = interval;
    this.canceled = false;
    
    this.observers = new Array();
    this.timerId = 0;
    this.xmlRequest = null;
    this.cancelNotifications = false;

    // Crear objeto XmlREquest Microsoft o Firefox
    Bankinter.Utils.Xml.DataSet.createXMLHttpRequest = function()
    {
	    var req = null;
	    try
	    {
		    if (window.XMLHttpRequest)
			    req = new XMLHttpRequest();
		    else if (window.ActiveXObject)
		    {
			    while (!req && Bankinter.Utils.Xml.msProgIDs.length)
			    {
				    try 
				    { 
				        req = new ActiveXObject(Bankinter.Utils.Xml.msProgIDs[0]); 
				    } 
				    catch (e) 
				    { 
				        req = null; 
				    }
				    if (!req)
					    Bankinter.Utils.msProgIDs.splice(0, 1);
			    }
		    }
	    }
	    catch (e) 
	    { 
	        req = null;	
	    }
	    return req;
    };
    
    
    Bankinter.Utils.Xml.DataSet.prototype.addObserver = function(observer)
    {
	    if (!observer)
		    return;

	    var len = this.observers.length;
	    for (var i = 0; i < len; i++)
	    {
		    if (this.observers[i] == observer)
			    return;
	    }
	    this.observers[len] = observer;
    };


    Bankinter.Utils.Xml.DataSet.prototype.removeObserver = function(observer)
    {
	    if (!observer)
		    return;

	    for (var i = 0; i < this.observers.length; i++)
	    {
		    if (this.observers[i] == observer)
		    {
			    this.observers.splice(i, 1);
			    break;
		    }
	    }
    };
    
    
    Bankinter.Utils.Xml.DataSet.prototype.notifyObservers = function(methodName, data)
    {
	    if (!methodName)
		    return;

        if (!this.cancelNotifications)
        {
	        var len = this.observers.length;
	        for (var i = 0; i < len; i++)
	        {
		        var obs = this.observers[i];
		        if (obs)
		        {
		            // La guarda es una precaucion pues no sabemos cual sera
		            // el comportamiento de los observadores
		            try
		            {
			            if (typeof obs == "function")
				            obs(methodName, this, data);
			            else if (obs[methodName])
				            obs[methodName](this, data);
				    }
				    catch(e)
				    {
				    }
		        }
	        }
	    }
    };
    
    
    Bankinter.Utils.Xml.DataSet.CreateObjectForNode = function(node)
    {
	    if (!node)
		    return null;

	    var obj = null;
	    var i = 0;
	    var attr = null;

	    try
	    {
		    for (i = 0; i < node.attributes.length; i++)
		    {
			    attr = node.attributes[i];
			    if (attr && attr.nodeType == 2 /* Node.ATTRIBUTE_NODE */)
			    {
				    if (!obj)
				    {
					    obj = new Object();
					    if (!obj)
					    {
						    return null;
					    }
				    }
    		
				    obj["@" + attr.name] = attr.value;
			    }
		    }
	    }
	    catch (e)
	    {
	    }
      
	    var child = node.firstChild;
    	
	    if (child && !child.nextSibling && child.nodeType != 1 /* Node.ELEMENT_NODE */)
	    {
		    if (!obj)
		    {
			    obj = new Object();
			    if (!obj)
			    {
				    return null;
			    }
		    }

		    obj[node.nodeName] = Bankinter.Utils.Xml.getNodeText(node);
	    }
      
	    while (child)
	    {  	
		    if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
		    {
			    if (!Bankinter.Utils.Xml.nodeContainsElementNode(child))
			    {
				    var txt = Bankinter.Utils.Xml.getNodeText(child);
				    if (!obj)
				    {
					    obj = new Object();
					    if (!obj)
					    {
						    return null;
					    }
				    }
    	  
				    obj[child.nodeName] = txt;

				    try
				    {
					    var namePrefix = child.nodeName + "/@";
    					
					    for (i = 0; i < child.attributes.length; i++)
					    {
						    attr = child.attributes[i];
						    if (attr && attr.nodeType == 2 /* Node.ATTRIBUTE_NODE */)
							    obj[namePrefix + attr.name] = attr.value;
					    }
				    }
				    catch (e)
				    {
				    }
            
			    }
		    }

		    child = child.nextSibling;
	    }
      
	    return obj;
    };   
    
    
    Bankinter.Utils.Xml.DataSet.arrayFromXmlDoc = function(doc, xpath)
    {
	    var recordSet = new Array();
	    
	    var ctx = new ExprContext(doc);
	    var pathExpr = xpathParse(xpath);
	    var e = pathExpr.evaluate(ctx);

	    var nodeArray = e.nodeSetValue();

	    var isDOMNodeArray = true;

	    if (nodeArray && nodeArray.length > 0)
		    isDOMNodeArray = nodeArray[0].nodeType != 2;

	    var nextID = 0;

	    for (var i = 0; i < nodeArray.length; i++)
	    {
		    var rowObj = null;
    	
		    if (isDOMNodeArray)
			    rowObj = Bankinter.Utils.Xml.DataSet.CreateObjectForNode(nodeArray[i]);
		    else 
		    {
			    rowObj = new Object;
			    rowObj["@" + nodeArray[i].name] = nodeArray[i].value;
		    }
    	
		    if (rowObj)
		    {
    		    rowObj['tuplaID'] = nextID++;
			    recordSet.push(rowObj);
		    }
	    }
      
	    return recordSet;    
    };
    
    
    Bankinter.Utils.Xml.DataSet.prototype.responseCompleted = function(request, self)
    {
        var xmlDoc = request.responseXML;
        
        if (request.status != 200 || !xmlDoc  || !xmlDoc.firstChild || xmlDoc.firstChild.nodeName == "parsererror" )
            self.notifyObservers("onLoadError", request);
         else
            self.notifyObservers("onPostLoad", Bankinter.Utils.Xml.DataSet.arrayFromXmlDoc(xmlDoc, self.xpath));
     };
        
    
    Bankinter.Utils.Xml.DataSet.requestStateChanged = function(self)
    {
        try
        {
            if (self.xmlRequest.readyState == 4) 
            {
                
                self.responseCompleted(self.xmlRequest, self);
              
                // Rearmar el temporizador para continuar el ciclo de refrescos si 
                // no se ha solicitado cancelar
                 
                if (!self.canceled)    
                {
                    self.timerId = setInterval(function() {self.onTimerElapsed();}, self.interval);  
                }
            }
        }
        catch(e)
        {
        };    
    };
        
    
    Bankinter.Utils.Xml.DataSet.prototype.onTimerElapsed = function()
    {
        var self = this;
        window.clearInterval(self.timerId);
        self.timerId = 0;
                 
        try
        {   
            // Es necesario desechar el objeto XmlHttpRequest debido a un
            // bug de Firefox, si se usa solo IE se pueden eliminar las dos
            // asignaciones siguientes:
        
            self.xmlRequest = Bankinter.Utils.Xml.DataSet.createXMLHttpRequest(); 
            self.xmlRequest.onreadystatechange = 
                function() {Bankinter.Utils.Xml.DataSet.requestStateChanged(self);};
            self.xmlRequest.open("GET", self.url, true);

            self.xmlRequest.send(null);  
        }
        catch(e)
        {
        } 
    };
    
    
    Bankinter.Utils.Xml.DataSet.prototype.setRefreshInterval = function(inter)
    {
        this.interval = inter;
    };
    
    
    Bankinter.Utils.Xml.DataSet.prototype.startRefreshInterval = function(start, interval)
    {
        var self = this;
        
        if (true == start)
        {
            this.startRefreshInterval(false);
            
            if (typeof interval != "undefined") self.interval = interval;
            
            // Crear el objeto HttpRequest y asignarle una funcion de 
            // callback a la que se pasa una ref. al objeto actual pues como
            // es frecuente esta callback debe ser estática
            
            self.xmlRequest = Bankinter.Utils.Xml.DataSet.createXMLHttpRequest();
            self.xmlRequest.onreadystatechange = 
                function() {Bankinter.Utils.Xml.DataSet.requestStateChanged(self);};
                
            self.canceled = false;    
            
            self.timerId = setInterval(function() {self.onTimerElapsed();}, self.interval); 
        }
        else
        {
            self.canceled = true;
            
            if (self.timerId != 0)
            {
                try
                {
                    window.clearInterval(self.timerId);
                    self.xmlRequest.abort();
                }
                catch(e) {}
                self.timerId = 0;
            }
            self.xmlRequest = null;
        }
    };
    
};


